package com.example.common.util.base642url;

import com.example.crud.sys.mapper.OrmMapper;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 按日期保留指定表数据
 *
 * @author zjarlin
 * @since 2023/02/14
 */
@Component
public class KeepDataByDate {
    @Autowired
    OrmMapper ormMapper;

    /**
     * 给定日期,往前推goback天,这个区间数据保留,其余删除
     *
     * @param tableName 表名
     * @param localDate 当地日期
     * @param goback    返回 入参
     * @author zjarlin
     * @since 2023/02/14
     */ // @SneakyThrows(Exception.class)
    @Transactional(rollbackFor = Exception.class)
    public void dataRetentionDaysBeforeAGivenDate(String tableName, String localDate, long goback) {
        LocalDate parse = LocalDate.parse(localDate);
        String localDateBeg = parse.toString();
        String localDateEnd = parse.minusDays(goback).toString();
        dataRetentionForAGivenDateRange(tableName, localDateBeg, localDateEnd);
    }

    /**
     * 给定日期范围数据保留
     *
     * @param tableName    表名
     * @param localDateBeg 当地日期最小
     * @param localDateEnd 当地日期最大
     * @author zjarlin
     * @since 2023/02/14
     */
    @Transactional(rollbackFor = Exception.class)
    public void dataRetentionForAGivenDateRange(String tableName, String localDateBeg, String localDateEnd) {
        LocalDate beg = LocalDate.parse(localDateBeg);
        LocalDate end = LocalDate.parse(localDateEnd);

        String left = getMinMaxOfOneDay(beg).getLeft().toString();
        String right = getMinMaxOfOneDay(end).getRight().toString();
        ormMapper.dataRetentionForAGivenDateRange(tableName, left, right);
    }

    private static Pair<LocalDateTime, LocalDateTime> getMinMaxOfOneDay(final LocalDate localDate) {
        LocalDateTime start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(localDate, LocalTime.MAX);
        Pair<LocalDateTime, LocalDateTime> of = Pair.of(start, end);
        return of;
    }

}
